package com.ssm.config;

import com.ssm.trace.TraceIdFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 自定义链路追踪过滤器
 * FilterRegistrationBean是Spring Framework 中的一个类，它用于在 Spring 容器中注册 Servlet 过滤器（Filter）。
 */
@Configuration
@ConditionalOnProperty(name = {"traceId.filter.enable"}, havingValue = "true")
public class FilterConfig {

    @Resource
    private TraceIdFilter traceIdFilter;
    @Bean
    public FilterRegistrationBean registrationFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(traceIdFilter);      // 过滤器实例
        filterRegistrationBean.addUrlPatterns("/*"); // 设置需要拦截的url
        filterRegistrationBean.setName("traceIdFilter"); // 设置名称trace：跟踪、追踪 (这个名称在 Servlet 容器中必须是唯一的。)
        filterRegistrationBean.setOrder(1); //优先级 越小越好
        return filterRegistrationBean;
    }

}
